<?php

// 会员表

namespace app\shop\model;

use think\Db;
use think\Model;
use think\Session;
use think\Request;
use app\shop\model\LotteryCode as LotteryCodeModel;

class Member extends Model
{

    protected static function init()
    {
        self::event('before_insert', function ($data) {
            $data->username = Request::instance()->param('username');
            $data->password = mcs(Request::instance()->param('password'));
            $data->create_ip = getIP();
            $data->create_time = time();
            $data->integral = 0;
        });


        self::event('before_write', function ($data) {
            if (!empty(Request::instance()->file('avatar'))) $data->avatar = uploadPc('avatar');
            if (!empty(Request::instance()->param('nickname'))) $data->nickname = Request::instance()->param('nickname');
            if (!empty(Request::instance()->param('sex'))) $data->sex = Request::instance()->param('sex');
            if (!empty(Request::instance()->param('name'))) $data->name = Request::instance()->param('name');
        });
    }


    public function registerMember()
    {
        // 获取数据
        $data = Request::instance()->param();

        $data['password'] = mcs($data['password']);

        $this->allowField(true)->save($data);

        // 获取新增会员ID
        $member_id = $this->id;

        Db::startTrans();

        try{
            // 注册分销系统
            if (!empty($data['referrals_id'])) {

                $this->distribution($data['referrals_id'], $member_id);
            } else {
                $ref_id = 0;
                $this->distribution($ref_id, $member_id);
            }

            //附加会员佣金表
            self::add_brokerage($member_id);

            // 抽奖码
            self::create_lottery_code($member_id);

            // 获取会员ID
            Session::set('member_id',$member_id);

            $content = "您好新用户，您的邀请码为：".$member_id;
            sendSMS($data['username'], $content);

            Db::commit();

            return true;
        }catch (\Exception $e) {

            Db::rollback();

            return false;
        }

    }


    /**
     * 新增会员分销关系表
     * @param $referrals_id
     * @param $member_id
     */
    public function distribution($referrals_id, $member_id)
    {

        $find = Db::name('MemberDistribution')->where(['referrals_id' => $referrals_id])->find();

        if (!empty($find['hierarchy'])) {
            $new_distribution = $find['hierarchy'] . $find['referrals_id'] . ',';
        } else {
            $new_distribution = $referrals_id . ',';
        }


        if (!empty($find['level'])) {
            $level = (int)$find['level'] + 1;
        } else {
            $level = 1;
        }

        $ini = [
            'distribution_id' => $referrals_id,
            'referrals_id'    => $member_id,
            'hierarchy'       => $new_distribution,
            'level'           => $level,
            'create_time'     => time(),
        ];
        Db::name('MemberDistribution')->insert($ini);

    }

    /**
     * 新增会员佣金表
     * @param $member_id
     */
    public function add_brokerage($member_id)
    {
        $map['member_id'] = $member_id;
        $map['general_income'] = 0;
        $map['to_yield'] = 0;
        $map['to_audit'] = 0;
        $map['actual_amount'] = 0;
        Db::name('MemberBrokerage')->insert($map);
    }


    /**
     * 生成抽奖码
     * @param $member_id
     */
    public function create_lottery_code($member_id)
    {
        $model = new LotteryCodeModel();
        //获取最后一条信息
        $find = $model->max('lottery_code');

        if ($find) {
            $lottery_code = (int)$find + 1;
        } else {
            $lottery_code = 1000001;
        }

        $ini = [
            'lottery_code' => $lottery_code,
            'member_id'    => $member_id,
            'type_id'      => 1,
            'create_time'  => time(),
        ];

        $model->save($ini);

    }

}